import { logout, getUserInfo, setAvatar } from '@/api/user'
import { login } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/token'
import { updateUserInfo } from '../../api/user'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {
      id: null,
      name: null,
      username: null,
      avatar: null,
      gender: null,
      phone: null,
      birthday: null
    }
  }
}

const defaultState = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  },
  SET_AVATAR: (state, avatar) => {
    state.userInfo = {
      ...state.userInfo,
      avatar
    }
  },
  UPDATE_USERINFO: (state, payload) => {
    state.userInfo = {
      ...state.userInfo,
      ...payload
    }
  }
}

const actions = {
  // user login
  async login({ commit }, user) {
    const { data: token } = await login(user)
    commit('SET_TOKEN', token)
    setToken(token)
    return token
  },
  // user logout
  async logout({ commit, state }) {
    await logout()
    removeToken() // must remove  token  first
    commit('RESET_STATE')
  },
  // get user info
  async getInfo({ commit, state }) {
    const { code, data } = await getUserInfo(state.token)
    if (code === 0) {
      commit('SET_USERINFO', data)
      return data
    }
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  async setAvatar({ commit }, payload) {
    const res = await setAvatar(payload)
    const { code, data } = res
    if (code === 0) {
      commit('SET_AVATAR', data)
    }
    return res
  },
  async updateUserInfo({ commit }, payload) {
    const res = await updateUserInfo(payload)
    const { code } = res
    if (code === 0) {
      commit('UPDATE_USERINFO', payload)
    }
    return res
  }
}

export default {
  namespaced: true,
  state: defaultState,
  mutations,
  actions
}

